package com.chmingx.springcloud.service;

import cn.hutool.core.util.IdUtil;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PathVariable;

import java.util.concurrent.TimeUnit;

@Service
public class PaymentService {
    // 正常访问
    public String paymentInfo_OK(Integer id) {
        return "线程池: " + Thread.currentThread().getName() + "\t" + "paymentInfo_OK, id: " + id + "\t" + "OK!!!";
    }

    /**
     * 该方法超时之后交给paymentInfo_TimeoutHandler进行处理
     */
    @HystrixCommand(fallbackMethod = "paymentInfo_TimeoutHandler", commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "1000") // 这个线程的超时时间是1秒， 也可以再yaml中配置
    })
    public String paymentInfo_Timeout(Integer id) {
        int timeNumber = 3;
//        int age = 10 / 0; // 刻意制造的异样，也可以由fallback方法处理
        try {
            TimeUnit.SECONDS.sleep(timeNumber);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "线程池: " + Thread.currentThread().getName() + "\t" + "paymentInfo_Timeout, id: " + id + "\t" + "OK!!!" + "\t" + "耗时: " + timeNumber;
    }

    // paymentInfo_Timeout 发生超时错误时的兜底方法, 注意服务降级的方法需要与原方法保持一致
    public String paymentInfo_TimeoutHandler(Integer id) {
        return "线程池: " + Thread.currentThread().getName() + "\t" + "系统繁忙或运行错误，请稍后再试" + "\t" + "Timeout!!!" + "\t" + "超时啦!!!";
    }

    // ---------- 服务熔断 ---------------
    @HystrixCommand(fallbackMethod = "paymentCircuitBreaker_fallback", commandProperties = {
            @HystrixProperty(name = "circuitBreaker.enabled", value = "true"), // 是否开启断路器
            @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold", value = "10"), // 请求次数
            @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds", value = "10000"), // 时间窗口期, 经过多久后恢复一次尝试
            @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage", value = "60") // 失败率达到多少后跳闸, 这个是概率，百分数
    })
    public String paymentCircuitBreaker(@PathVariable("id") Integer id) {
        if (id < 0) {
            throw new RuntimeException("****** id 不能为负数");
        }
        String serialNumber = IdUtil.simpleUUID(); // UUID.randomUUID().toString();

        return Thread.currentThread().getName() + "\t" + "调用成功，流水号: " + serialNumber;
    }

    public String paymentCircuitBreaker_fallback(@PathVariable("id") Integer id) {
        return "id 不能为负数，请稍后再试, T_T, id: " + id;
    }
}
